package com.dragon.gencode.conf.db;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 数据源配置类
 * 在该类中生成多个数据源实例并将其注入到 ApplicationContext 中
 * 2019年6月4日 上午10:06:54
 */
@Configuration
public class DataSourceConfigurer {

    /**
     * 配置数据源
     * @return
     */
    @Bean(name = "gen")
    @Primary
    @ConfigurationProperties("spring.datasource.gen")
    public DataSource gen() {
    	return DruidDataSourceBuilder.create().build();
    }
    
    /**
     * 配置数据源
     * @return
     */
    @Bean(name = "genConf")
    @ConfigurationProperties(prefix = "spring.datasource.gen-conf")
    public DataSource genConf() {
    	return DruidDataSourceBuilder.create().build();
    }

    /**
     * 配置数据源
     * @return
     */
    @Bean(name = "genSqlite")
    @ConfigurationProperties(prefix = "spring.datasource.gen-sqlite")
    public DataSource genSqlite() {
    	return DruidDataSourceBuilder.create().build();
    }

    /**
     * jdbcTemplate
     * @return
     */
    @Bean(name = "jdbcTemplate")
    public JdbcTemplate jdbcTemplate(@Qualifier("dynamicDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @Bean(name = "dynamicDataSource")
    public DataSource dynamicDataSource(){
    	DynamicRoutingDataSource dynamicRoutingDataSource = new DynamicRoutingDataSource();
    	
    	Map<Object, Object> dataSourceMap = new HashMap<Object, Object>(4);
    	dataSourceMap.put(DynamicDataSourceContextHolder.DataSourceKey.GEN.getName(),gen());
    	dataSourceMap.put(DynamicDataSourceContextHolder.DataSourceKey.GEN_CONF.getName(),genConf());
    	dataSourceMap.put(DynamicDataSourceContextHolder.DataSourceKey.GEN_SQLITE.getName(),genSqlite());

    	dynamicRoutingDataSource.setDefaultTargetDataSource(gen());
    	dynamicRoutingDataSource.setTargetDataSources(dataSourceMap);
    	
    	DynamicDataSourceContextHolder.dataSourceKeys.addAll(dataSourceMap.keySet());
    
    	return dynamicRoutingDataSource;
    }
}